﻿using System;
using System.Data.SqlClient;
using System.Drawing;
using System.IO.Ports;
using System.Windows.Forms;

namespace FerriteZone
{
    public partial class Ferrite_Zone : Form
    {
        private String InputData_Ferrite = String.Empty;

        private delegate void SetTextCallback(string text);

        private String InputData_tmpFerrite = String.Empty;

        private Function f = new Function();

        private String strConn = "Data Source=163.50.57.11\\sqlt;Initial Catalog=MT300_Mixing;Integrated Security=True";

        public Ferrite_Zone()
        {
            InitializeComponent();
           
        }

        public void hideFerrite_2()
        {
            lb_Just_2.Hide();
            lb_Ferrite_2.Hide();
            lb_SumFerrite_2.Hide();
            tb_Ferrite_2.Hide();
            lb_Ferrute_kg_2.Hide();
            lb_error_2.Hide();
        }

        public void ShowFerrite_2()
        {
            lb_Just_2.Show();
            lb_Ferrite_2.Show();
            lb_SumFerrite_2.Show();
            tb_Ferrite_2.Show();
            lb_Ferrute_kg_2.Show();
            lb_error_2.Show();
        }

        private void Ferrite_Zone_Load(object sender, EventArgs e)
        {
            try
            {
                using (SqlConnection connection = new SqlConnection(strConn))
                {
                    connection.Open();
                    using (SqlCommand command = connection.CreateCommand())
                    {
                        command.CommandText = "SELECT * From Emp_ID WHERE Position = 'mit'";

                        SqlDataReader reader = command.ExecuteReader();
                        SqlDataReader tmp = reader;

                        while (reader.Read())
                        {
                            cb_ID.Items.Add(reader["Emp_ID"]);
                        }
                    }
                }
            }
            catch
            {
                lb_Status.Text = "Network Failed";
            }

            comPort();
            AutoConfig();
        }

        public void comPort()
        {
            string[] ports = SerialPort.GetPortNames();

            foreach (string port in ports)
            {
                cb_Serial_List.Items.Add(port);
            }
        }

        private void cb_ID_SelectedIndexChanged(object sender, EventArgs e)
        {
            tb_LotID.Focus();
            lb_Status.Text = cb_ID.Text;
        }

        private void tb_LotID_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Back)
            {
                DialogResult dialogResult = MessageBox.Show("คุณต้องการลบข้อความนี้ ใช่ หรือ ไม่", "คุณแน่ใจ", MessageBoxButtons.YesNo);
                if (dialogResult == DialogResult.Yes)
                {
                    tb_LotID.Text = "";
                }
            }
            else if (e.KeyCode == Keys.Enter && cb_ID.Text == "")
            {
                tb_LotID.Text = "";
                lb_Status.Text = "เลือกรหัสพนักงาน";
            }
            else if (e.KeyCode == Keys.Enter)
            {
                tb_SLMPart.Focus();
            }
        }

        private void tb_SLMPart_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Back)
            {
                DialogResult dialogResult = MessageBox.Show("คุณต้องการลบข้อความนี้ ใช่ หรือ ไม่", "คุณแน่ใจ", MessageBoxButtons.YesNo);
                if (dialogResult == DialogResult.Yes)
                {
                    tb_SLMPart.Text = "";
                }
            }
            else if (e.KeyCode == Keys.Enter && tb_LotID.Text == "")
            {
                tb_SLMPart.Text = "";
                lb_Status.Text = "สแกนล็อต";
            }
            else if (e.KeyCode == Keys.Enter)
            {
                try
                {
                    using (SqlConnection connection = new SqlConnection(strConn))
                    {
                        connection.Open();
                        using (SqlCommand command = connection.CreateCommand())
                        {
                            command.CommandText = "SELECT * From SLM_Part WHERE  SLMPart like'%" + f.findSLMPart(tb_SLMPart.Text) + "%'";

                            SqlDataReader reader = command.ExecuteReader();
                            while (reader.Read())
                            {
                                if (reader["Ferrite"].ToString().Split('?').Length == 1)
                                {
                                    lb_Ferrite_1.Text = reader["Ferrite"].ToString().Split('?')[0].Split('#')[0];
                                    lb_Ferrute_kg_1.Text = reader["Ferrite"].ToString().Split('?')[0].Split('#')[1].Split('@')[0];
                                    lb_error_1.Text = reader["Ferrite"].ToString().Split('?')[0].Split('#')[1].Split('@')[1];
                                    hideFerrite_2();
                                }
                                else if (reader["Ferrite"].ToString().Split('?').Length == 2)
                                {
                                    ShowFerrite_2();

                                    lb_Ferrite_1.Text = reader["Ferrite"].ToString().Split('?')[0].Split('#')[0];
                                    lb_Ferrute_kg_1.Text = reader["Ferrite"].ToString().Split('?')[0].Split('#')[1].Split('@')[0];
                                    lb_error_1.Text = reader["Ferrite"].ToString().Split('?')[0].Split('#')[1].Split('@')[1];

                                    lb_Ferrite_2.Text = reader["Ferrite"].ToString().Split('?')[1].Split('#')[0];
                                    lb_Ferrute_kg_2.Text = reader["Ferrite"].ToString().Split('?')[1].Split('#')[1].Split('@')[0];
                                    lb_error_2.Text = reader["Ferrite"].ToString().Split('?')[1].Split('#')[1].Split('@')[1];
                                }
                                tb_FerriteType.Focus();
                            }//while
                        }
                    }
                }
                catch
                {
                    lb_Status.Text = "ไม่พบข้อมูล";
                }

                if (f.SearchString(tb_SLMPart.Text, "18"))
                {
                    btn_Add_1.Show();
                }
                else
                {
                    btn_Add_1.Hide();
                }

                lb_Status.Text = "งานรุ่น " + tb_SLMPart.Text;
            }//else if
        }

        private void serialPort_Ferrite_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
        {
            try
            {
                InputData_Ferrite = serialPort_Ferrite.ReadLine();
                if (InputData_Ferrite != String.Empty)
                {
                    if (InputData_Ferrite.Substring(0, 2) == "wn")
                    {
                        SetText_Ferrite(InputData_Ferrite);
                    }
                }
            }
            catch
            {
                lb_Status.Text = "ไม่สามารถรับส่งข้อมูลได้";
            }
        }//func

        private void SetText_Ferrite(string text)
        {
            if (this.tb_Ferrite_1.InvokeRequired)
            {
                SetTextCallback d = new SetTextCallback(SetText_Ferrite);
                this.Invoke(d, new object[] { text });
            }
            else
            {
                try
                {
                    if (f.SearchString(tb_FerriteType.Text, lb_Ferrite_1.Text))
                    {
                        tb_Ferrite_1.Text = Double.Parse(text.Replace(" ", String.Empty).Replace("wn", String.Empty).Replace("kg", String.Empty).Replace("GS", String.Empty).Replace("g", String.Empty)).ToString();
                    }
                    else if (f.SearchString(tb_FerriteType.Text, lb_Ferrite_2.Text))
                    {
                        tb_Ferrite_2.Text = Double.Parse(text.Replace(" ", String.Empty).Replace("wn", String.Empty).Replace("kg", String.Empty).Replace("GS", String.Empty).Replace("g", String.Empty)).ToString();
                    }
                }
                catch
                {
                    lb_Status.Text = "Set Text Error";
                }
            }
        }

        private void tb_Comfirm_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Back)
            {
                DialogResult dialogResult = MessageBox.Show("คุณแน่ใจหรือไม่ ว่าจะลบข้อความนี้", "คุณแน่ใจ", MessageBoxButtons.YesNo);
                if (dialogResult == DialogResult.Yes)
                {
                    tb_FerriteType.Text = "";
                }
            }
            else if (e.KeyCode == Keys.Enter)
            {
                if (f.SearchString(tb_FerriteType.Text, lb_Ferrite_1.Text))
                {
                    lb_Status.Text = lb_Ferrite_1.Text;
                }
                else if (f.SearchString(tb_FerriteType.Text, lb_Ferrite_2.Text))
                {
                    lb_Status.Text = lb_Ferrite_2.Text;
                }
                else
                {
                    lb_Status.Text = "ไม่พบผงเฟอร์ไรต์";
                }
            }
        }

        private void lb_SumFerrite_2_TextChanged(object sender, EventArgs e)
        {
            try
            {
                double Ferrite_2 = Double.Parse("0" + lb_Ferrute_kg_2.Text);
                double Error_2 = Double.Parse("0" + lb_error_2.Text);
                double com = Double.Parse("0" + lb_SumFerrite_2.Text);
                if (com >= (Ferrite_2 - Error_2) && com <= (Ferrite_2 + Error_2))
                {
                    lb_Just_2.Text = "G";
                    lb_Just_2.BackColor = Color.Green;
                    lb_Just_2.ForeColor = Color.White;
                }
                else
                {
                    lb_Just_2.Text = "NG";
                    lb_Just_2.BackColor = Color.Green;
                    lb_Just_2.ForeColor = Color.White;
                }
            }
            catch
            {
                //
            }

            try
            {
                using (SqlConnection connection = new SqlConnection(strConn))
                {
                    connection.Open();
                    using (SqlCommand command = connection.CreateCommand())
                    {
                        command.CommandText = "INSERT INTO History_Ferrite (LotNumber, SLMPart,Emp_ID,Ferrite_1,Ferrite_2, Datetimes, Status_1, Status_2,Ferrite_weight_1,Ferrite_weight_2) VALUES (@LotNumber, @SLMPart,@Emp_ID,@Ferrite_1,@Ferrite_2, @Datetimes, @Status_1, @Status_2,@Ferrite_weight_1, @Ferrite_weight_2 )";

                        command.Parameters.AddWithValue("@LotNumber", tb_LotID.Text);
                        command.Parameters.AddWithValue("@SLMPart", tb_SLMPart.Text);
                        command.Parameters.AddWithValue("@Emp_ID", cb_ID.Text);
                        command.Parameters.AddWithValue("@Datetimes", f.dataTime());

                        command.Parameters.AddWithValue("@Ferrite_1", lb_Ferrite_1.Text);
                        command.Parameters.AddWithValue("@Ferrite_weight_1", lb_SumFerrite_1.Text);
                        command.Parameters.AddWithValue("@Status_1", lb_Just_1.Text);

                        if (f.SearchString(tb_FerriteType.Text, lb_Ferrite_2.Text) && tb_Ferrite_2.Text != "")
                        {
                            command.Parameters.AddWithValue("@Ferrite_2", lb_Ferrite_2.Text);
                            command.Parameters.AddWithValue("@Ferrite_weight_2", lb_SumFerrite_2.Text);
                            command.Parameters.AddWithValue("@Status_2", lb_Just_2.Text);
                        }
                        command.ExecuteNonQuery();
                    }
                }
            }
            catch
            {
                lb_Status.Text = "Error";
            }
        }

        private void lb_SumFerrite_1_TextChanged(object sender, EventArgs e)
        {
            try
            {
                double Ferrite_1 = Double.Parse("0" + lb_Ferrute_kg_1.Text);
                double Error_1 = Double.Parse("0" + lb_error_1.Text);
                double com = Double.Parse("0" + lb_SumFerrite_1.Text);
                if (com >= (Ferrite_1 - Error_1) && (com <= Ferrite_1 + Error_1))
                {
                    lb_Just_1.Text = "G";
                    lb_Just_1.BackColor = Color.Green;
                    lb_Just_1.ForeColor = Color.White;
                }
                else
                {
                    lb_Just_1.Text = "NG";
                    lb_Just_1.BackColor = Color.Red;
                    lb_Just_1.ForeColor = Color.White;
                }
            }
            catch
            {
                //
            }

            try
            {
                using (SqlConnection connection = new SqlConnection(strConn))
                {
                    connection.Open();
                    using (SqlCommand command = connection.CreateCommand())
                    {
                        command.CommandText = "INSERT INTO History_Ferrite (LotNumber, SLMPart,Emp_ID, Ferrite_1, Ferrite_weight_1, Status_1, Datetimes) VALUES (@LotNumber, @SLMPart,@Emp_ID, @Ferrite_1, @Ferrite_weight_1, @Status_1, @Datetimes)";

                        command.Parameters.AddWithValue("@LotNumber", tb_LotID.Text);
                        command.Parameters.AddWithValue("@SLMPart", tb_SLMPart.Text);
                        command.Parameters.AddWithValue("@Emp_ID", cb_ID.Text);
                        command.Parameters.AddWithValue("@Datetimes", f.dataTime());

                        if (f.SearchString(tb_FerriteType.Text, lb_Ferrite_1.Text))
                        {
                            command.Parameters.AddWithValue("@Ferrite_1", lb_Ferrite_1.Text);
                            command.Parameters.AddWithValue("@Ferrite_weight_1", lb_SumFerrite_1.Text);
                            command.Parameters.AddWithValue("@Status_1", lb_Just_1.Text);
                        }
                        command.ExecuteNonQuery();
                    }
                }
            }
            catch
            {
                lb_Status.Text = "Error";
            }
        }

        private void btn_Add_1_Click(object sender, EventArgs e)
        {
            string txt = tb_SLMPart.Text;
            if (f.SearchString(tb_SLMPart.Text, "18"))
            {
                double a = Double.Parse("0" + lb_SumFerrite_1.Text);
                double b = Double.Parse("0" + tb_Ferrite_1.Text);
                lb_SumFerrite_1.Text = a + b + "";
                tb_Ferrite_1.Text = "";
                tb_FerriteType.Text = "";
            }
        }

        public void Ferrite_config(String txt)
        {
            if (serialPort_Ferrite.IsOpen)
                serialPort_Ferrite.Close();
            serialPort_Ferrite.PortName = txt;
            serialPort_Ferrite.BaudRate = 9600;
            serialPort_Ferrite.StopBits = StopBits.One;
            serialPort_Ferrite.Parity = Parity.None;
            serialPort_Ferrite.DataBits = 8;

            try
            {
                serialPort_Ferrite.Open();
            }
            catch
            {
                serialPort_Ferrite.Close();
            }
        }

        private void btn_Connect_Click(object sender, EventArgs e)
        {
            cb_Serial_List.Enabled = true;
            cb_Serial_List.Items.Remove(serialPort_Ferrite.PortName);
            comPort();
        }

        private void tb_Ferrite_2_TextChanged(object sender, EventArgs e)
        {
            lb_SumFerrite_2.Text = tb_Ferrite_2.Text;
        }

        private void tb_Ferrite_1_TextChanged(object sender, EventArgs e)
        {
            if (!f.SearchString(tb_SLMPart.Text, "18"))
            {
                lb_SumFerrite_1.Text = tb_Ferrite_1.Text;
            }
        }

        private void cb_Serial_List_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (cb_Serial_List.Text != "")
            {
                Ferrite_config(cb_Serial_List.SelectedItem.ToString());
                cb_Serial_List.Enabled = false;
            }
        }

        private void btn_Save_Click(object sender, EventArgs e)
        {
            try
            {
                using (SqlConnection connection = new SqlConnection(strConn))
                {
                    connection.Open();
                    using (SqlCommand command = connection.CreateCommand())
                    {
                        command.CommandText = "INSERT INTO History_Ferrite (LotNumber, SLMPart,Emp_ID,Ferrite_1,Ferrite_2, Datetimes, Status_1, Status_2,Ferrite_weight_1,Ferrite_weight_2) VALUES (@LotNumber, @SLMPart,@Emp_ID,@Ferrite_1,@Ferrite_2, @Datetimes, @Status_1, @Status_2,@Ferrite_weight_1, @Ferrite_weight_2 )";

                        command.Parameters.AddWithValue("@LotNumber", tb_LotID.Text);
                        command.Parameters.AddWithValue("@SLMPart", tb_SLMPart.Text);
                        command.Parameters.AddWithValue("@Emp_ID", cb_ID.Text);
                        command.Parameters.AddWithValue("@Datetimes", f.dataTime());

                        command.Parameters.AddWithValue("@Ferrite_1", lb_Ferrite_1.Text);
                        command.Parameters.AddWithValue("@Ferrite_weight_1", lb_SumFerrite_1.Text);
                        command.Parameters.AddWithValue("@Status_1", lb_Just_1.Text);

                        command.Parameters.AddWithValue("@Ferrite_2", lb_Ferrite_1.Text);
                        command.Parameters.AddWithValue("@Ferrite_weight_2", lb_SumFerrite_2.Text);
                        command.Parameters.AddWithValue("@Status_2", lb_Just_2.Text);

                        command.ExecuteNonQuery();
                    }
                }
            }
            catch
            {
                lb_Status.Text = "Error";
            }

            this.Controls.Clear();
            this.InitializeComponent();
        }

        private void tb_LotSreach_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Back)
            {
                DialogResult dialogResult = MessageBox.Show("คุณต้องการลบข้อความนี้ ใช่ หรือ ไม่", "คุณแน่ใจ", MessageBoxButtons.YesNo);
                if (dialogResult == DialogResult.Yes)
                {
                    tb_SLMPart.Text = "";
                }
            }
            else if (e.KeyCode == Keys.Enter)
            {
                lsv_Reports.Clear();

                lsv_Reports.Columns.Add("เลขล๊อต", 150, HorizontalAlignment.Center);
                lsv_Reports.Columns.Add("รุ่นงาน", 150, HorizontalAlignment.Center);

                lsv_Reports.Columns.Add("เฟอรไรต์ 1", 150, HorizontalAlignment.Center);
                lsv_Reports.Columns.Add("น้ำหนัก", 150, HorizontalAlignment.Center);
                lsv_Reports.Columns.Add("สถานะ", 150, HorizontalAlignment.Center);

                lsv_Reports.Columns.Add("เฟอรไรต์ 2", 150, HorizontalAlignment.Center);
                lsv_Reports.Columns.Add("น้ำหนัก", 150, HorizontalAlignment.Center);
                lsv_Reports.Columns.Add("สถานะ", 150, HorizontalAlignment.Center);

                lsv_Reports.Columns.Add("พนักงาน", 150, HorizontalAlignment.Center);
                lsv_Reports.Columns.Add("ว/ด/ป", 150, HorizontalAlignment.Center);

                lsv_Reports.View = View.Details;
                lsv_Reports.GridLines = true;
                lsv_Reports.FullRowSelect = true;

                try
                {
                    using (SqlConnection connection = new SqlConnection(strConn))
                    {
                        connection.Open();
                        using (SqlCommand command = connection.CreateCommand())
                        {
                            command.CommandText = "SELECT TOP 1 * From History_Ferrite WHERE LotNumber ='" + tb_LotSreach.Text + "' AND( Status_1='G' OR Status_2='G') ORDER BY Datetimes DESC";

                            SqlDataReader reader = command.ExecuteReader();
                            while (reader.Read())
                            {
                                String LotNumber = reader["LotNumber"].ToString();

                                String Emp_ID = reader["Emp_ID"].ToString();
                                String SLMPart = reader["SLMPart"].ToString();

                                String Ferrite_1 = reader["Ferrite_1"].ToString();
                                String Ferrite_2 = reader["Ferrite_2"].ToString();

                                String Datetimes = reader["Datetimes"].ToString();

                                String Status_1 = reader["Status_1"].ToString();
                                String Status_2 = reader["Status_2"].ToString();

                                String Ferrite_weight_1 = reader["Ferrite_weight_1"].ToString();
                                String Ferrite_weight_2 = reader["Ferrite_weight_2"].ToString();

                                ListViewItem listitem = new ListViewItem(LotNumber);

                                listitem.SubItems.Add(SLMPart);

                                listitem.SubItems.Add(Ferrite_1);
                                listitem.SubItems.Add(Ferrite_weight_1);
                                listitem.SubItems.Add(Status_1);

                                listitem.SubItems.Add(Ferrite_2);
                                listitem.SubItems.Add(Ferrite_weight_2);
                                listitem.SubItems.Add(Status_2);

                                listitem.SubItems.Add(Emp_ID);
                                listitem.SubItems.Add(Datetimes);

                                lsv_Reports.Items.Add(listitem);
                            }
                        }
                    }
                }
                catch
                {
                    lb_Status.Text = "Network Failed";
                }
            }
        }

        public void AutoConfig()
        {
            try
            {

                serialPort_Ferrite.Close();
            }
            catch
            {
                //
            }

            try
            {
                string[] lines = System.IO.File.ReadAllLines(@"C:\Users\Public\FerriteZone.txt");
                cb_Serial_List.SelectedIndex = cb_Serial_List.FindString(lines[0].ToString());
            }
            catch
            {
                serialPort_Ferrite.Close();
            }
        }

    }
}
